'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { 
  Table, 
  Button, 
  Input, 
  Select, 
  Card, 
  Tag, 
  Space, 
  Message,
  Tooltip,
  Badge,
} from '@arco-design/web-react';
import { 
  IconSearch, 
  IconSettings, 
  IconDownload, 
  IconUpload, 
  IconEye,
  IconCloud,
  IconStorage,
  IconBranch,
  IconPlayArrow,
  IconCheckCircle,
  IconArchive,
  IconThunderbolt,
} from '@arco-design/web-react/icon';
import { modelsAPI } from '@/services/modelsAPI';
import { Model } from '@/types/api';
import ImportModelModal from '@/app/models/components/ImportModelModal';

const Option = Select.Option;

export default function ModelsPage() {
  const [models, setModels] = useState<Model[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [typeFilter, setTypeFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [summary, setSummary] = useState<{[key: string]: number}>({});
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  
  // 导入弹窗状态
  const [importModalVisible, setImportModalVisible] = useState(false);

  const fetchModels = async (page = currentPage, size = pageSize) => { 
    try {
      setLoading(true);
      const params = {
        use_pagination: true,
        page: page,
        page_size: size,
        search: searchTerm || undefined,
        type: typeFilter !== 'all' ? typeFilter : undefined,
        status: statusFilter !== 'all' ? statusFilter : undefined,
      };
      
      const response = await modelsAPI.getModels(params);
      setModels(response.models || []);
      setSummary(response.summary || {});
      setTotal(response?.pagination?.total_count || 0);
      const totalCount = response?.pagination?.total_count || 0;
      Message.success(`模型列表加载成功，共 ${totalCount} 个模型`);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取模型列表失败';
      Message.error(`加载失败: ${errorMessage}`);
    } finally { 
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchModels();
  }, [currentPage, pageSize]);

  useEffect(() => {
    // 当搜索条件或筛选条件改变时，重置到第一页
    if (currentPage !== 1) {
      setCurrentPage(1);
    } else {
      fetchModels(1, pageSize);
    }
  }, [searchTerm, typeFilter, statusFilter]);

  const getStatusBadge = useCallback((status: string) => {
    switch (status) {
      case 'draft':
        return <Badge status="processing" text="训练完成" />;
      case 'published':
        return <Badge status="success" text="已发布" />;
      case 'archived':
        return <Badge status="default" text="已归档" />;
      default:
        return <Badge status="default" text={status} />;
    }
  }, []);

  const getDeploymentIcon = useCallback((type: string) => {
    switch (type) {
      case 'cloud':
        return <IconCloud className="text-primary-500" />;
      case 'edge':
        return <IconStorage className="text-primary-600" />;
      case 'both':
        return <IconBranch className="text-primary-700" />;
      default:
        return null;
    }
  }, []);

  const renderTags = useCallback((tags: string[]) => {
    if (!tags || tags.length === 0) return null;
    
    const colors = ['blue', 'green', 'purple', 'orange'];
    const displayTags = tags.slice(0, 4);
    
    return (
      <Space wrap>
        {displayTags.map((tag, index) => (
          <Tag key={`${tag}-${index}`} color={colors[index % colors.length]} size="small">
            {tag}
          </Tag>
        ))}
        {tags.length > 4 && (
          <Tag color="gray" size="small">
            +{tags.length - 4}
          </Tag>
        )}
      </Space>
    );
  }, []);

  const columns = React.useMemo(() => [
    {
      title: '模型信息',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      render: (_: any, record: Model) => (
        <div>
          <div className="font-medium text-sm">{record.name}</div>
          <div className="text-xs text-gray-500 mt-1">
            {record.description && record.description.length > 15 ? (
              <Tooltip content={record.description}>
                <span className="cursor-help">
                  {record.description.slice(0, 15)}...
                </span>
              </Tooltip>
            ) : (
              record.description
            )}
          </div>
          <div className="text-xs text-gray-400 mt-1 space-y-1">
            <div>创建: {record.createdAt}</div>
            <div>更新: {record.lastTrained}</div>
          </div>
        </div>
      ),
    },
    {
      title: '类型',
      dataIndex: 'tags',
      key: 'tags',
      width: 100,
      align: 'center' as const,
      render: (tags: string[]) => renderTags(tags),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      align: 'center' as const,
      render: (status: string) => getStatusBadge(status),
    },
    {
      title: '架构',
      dataIndex: 'architecture',
      key: 'architecture',
      width: 120,
      align: 'center' as const,
      render: (_: any, record: Model) => (
        <div>
          <div className="text-sm">{record.architecture}</div>
          <div className="text-xs text-gray-500">{record.framework}</div>
        </div>
      ),
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      width: 100,
      align: 'center' as const,
      render: (version: string) => (
        <Tag color="purple">{version}</Tag>
      ),
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      width: 100,
      align: 'center' as const,
      render: (size: string) => (
        <Space>
          <span className="text-sm font-medium">{size}</span>
        </Space>
      ),
    },
    {
      title: '准确率',
      dataIndex: 'accuracy',
      key: 'accuracy',
      width: 120,
      align: 'center' as const,
      render: (accuracy: number) => (
        <div>
          <div className="text-sm font-semibold text-primary-600 mt-1">
            {accuracy}%
          </div>
        </div>
      ),
    },
    {
      title: '部署',
      dataIndex: 'deploymentType',
      key: 'deploymentType',
      width: 100,
      align: 'center' as const,
      render: (type: string) => (
        <div className="flex items-center justify-center">
          {getDeploymentIcon(type)}
          <span className="ml-1 text-xs">
            {type === 'cloud' ? '云端' : type === 'edge' ? '边缘' : '混合'}
          </span>
        </div>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      align: 'center' as const,
      render: (_: any, record: Model) => (
        <Space>
          <Tooltip content="下载">
            <Button 
              type="text" 
              icon={<IconDownload />} 
              size="small" 
            />
          </Tooltip>
          <Tooltip content="设置">
            <Button 
              type="text" 
              icon={<IconSettings />} 
              size="small" 
            />
          </Tooltip>
          <Tooltip content="查看">
            <Button 
              type="text" 
              icon={<IconEye />} 
              size="small" 
            />
          </Tooltip>
        </Space>
      ),
    },
  ], [getStatusBadge, getDeploymentIcon, renderTags]);

  const handleImportModel = useCallback(() => {
    setImportModalVisible(true);
  }, []);

  const handleImportSubmit = useCallback(async (formData: any) => {
    try {
      console.log('导入模型数据:', formData);
      
      // 这里可以调用API提交数据
      // await modelsAPI.importModel(formData);
      
      Message.success('模型导入成功，正在处理中...');
      
      // 重新获取模型列表
      fetchModels();
    } catch (error) {
      Message.error('模型导入失败，请重试');
    }
  }, []);

  const handleImportModalClose = useCallback(() => {
    setImportModalVisible(false);
  }, []);



  return (
    <div className="p-0 m-0">
      <Space direction="vertical" className="w-full" size="large">
        {/* 标题栏 */}
        <div className="flex items-center justify-between flex-wrap gap-4">
          <div>
            <h1 className="text-xl font-bold m-0 text-gray-900">
              进化模型管理
            </h1>
            <p className="text-sm text-gray-500 mt-1 mb-0">
              模型部署与版本管理
            </p>
          </div>
          <Button 
            type="primary" 
            icon={<IconUpload />}
            onClick={handleImportModel}
          >
            导入
          </Button>
        </div>

        {/* 指标卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <Card>
            <div className="flex items-center justify-between">
              <div>
                <div className="text-xs font-medium text-primary-600 uppercase">
                  人员安全
                </div>
                <div className="text-2xl text-primary-600 font-bold mt-1">
                  {summary?.['人员安全'] ?? 0}
                </div>
              </div>
              <IconPlayArrow className="text-2xl text-primary-600" />
            </div>
          </Card>
          
          <Card>
            <div className="flex items-center justify-between">
              <div>
                <div className="text-xs font-medium text-primary-600 uppercase">
                  环境巡视
                </div>
                <div className="text-2xl text-primary-600 font-bold mt-1">
                {summary?.['环境巡视'] ?? 0}
                </div>
              </div>
              <IconCheckCircle className="text-2xl text-primary-600" />
            </div>
          </Card>
            
            <Card>
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-xs font-medium text-primary-600 uppercase">
                  设备运检I
                  </div>
                  <div className="text-2xl text-primary-600 font-bold mt-1">
                  {summary?.['设备运检I'] ?? 0}
                  </div>
                </div>
                <IconThunderbolt className="text-2xl text-primary-600" />
              </div>
            </Card>
            
            <Card>
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-xs font-medium text-primary-600 uppercase">
                  设备运检S
                  </div>
                  <div className="text-2xl text-primary-600 font-bold mt-1">
                    {summary?.['设备运检S'] ?? 0}
                  </div>
                </div>
                <IconArchive className="text-2xl text-primary-600" />
            </div>
          </Card>
        </div>

        {/* 搜索和筛选 */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <Input
            placeholder="搜索模型名称或描述..."
            prefix={<IconSearch />}
            value={searchTerm}
            onChange={setSearchTerm}
            allowClear
          />
          <Select
            placeholder="选择模型类型"
            value={typeFilter}
            onChange={setTypeFilter}
            allowClear
          >
            <Option value="all">全部类型</Option>
            <Option value="large">大模型</Option>
            <Option value="small">小模型</Option>
          </Select>
          <Select
            placeholder="选择状态"
            value={statusFilter}
            onChange={setStatusFilter}
            allowClear
          >
            <Option value="all">全部状态</Option>
            <Option value="training">训练中</Option>
            <Option value="ready">就绪</Option>
            <Option value="published">已发布</Option>
            <Option value="archived">已归档</Option>
          </Select>
        </div>

        {/* 模型表格 */}
        <Table
          columns={columns}
          data={models}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            current: currentPage,
            total: total,
            pageSize: pageSize,
            showTotal: true,
            showJumper: true,
            sizeCanChange: true,
            pageSizeChangeResetCurrent: false,
            onChange: (page, size) => {
              setCurrentPage(page);
              if (size !== pageSize) {
                setPageSize(size);
                setCurrentPage(1); // 改变页面大小时重置到第一页
              }
            },
            onPageSizeChange: (size) => {
              setPageSize(size);
              setCurrentPage(1);
            },
          }}
        />
        
        {/* 底部统计 */}
        <div className="border-t border-gray-200 bg-gray-50 p-3 mt-4 rounded-md">
          <div className="flex items-center justify-between text-sm text-gray-500 flex-wrap gap-4">
            <Space size="large">
              <span>共 {total} 个模型</span>
              <span>当前页: {models.length} 个</span>
              <span>第 {currentPage} 页 / 共 {Math.ceil(total / pageSize)} 页</span>
            </Space>
            <Space size="large">
              <span>
                平均准确率: {models && models.length > 0 ? Math.round(models.reduce((sum, m) => sum + m.accuracy, 0) / models.length) : 0}%
              </span>
              <span>每页显示: {pageSize} 条</span>
            </Space>
          </div>
        </div>
      </Space>

      {/* 导入模型弹窗 */}
      <ImportModelModal
        visible={importModalVisible}
        onClose={handleImportModalClose}
        onSubmit={handleImportSubmit}
      />
    </div>
  );
} 